﻿using ChoMy.Areas.Admin.Models;
using ChoMy.Constants;
using ChoMy.Helpers;
using ChoMy.Models;
using ChoMy.Models.Data;
using PagedList;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;

namespace ChoMy.Areas.Admin.Controllers
{
    public class PropertyController : Controller
    {
        private ChoMyContext db = new ChoMyContext();
        private StringHelper strHp = new StringHelper();
        private string title = "thuộc tính";

        public PropertyController()
        {
            ViewBag.Title = title;
        }

        [Authorize(Roles = "Admin, Property Read Public,  Property Read Private")]
        public ActionResult Index(int? propertyTypeId, bool? isTrash, string search, string sortOrder, int? page, int? pageSize)
        {
            var sortList = new List<string> { "Name", "DateModified", "DateCreated", "PropertyType.Name", "Value", "StyleProperties.Count" };
            var pageSizeList = new List<int> { 10, 25, 50, 100 };
            int pageNumber = page ?? 1;

            pageSize = pageSize ?? 10;
            sortOrder = sortOrder ?? "DateCreated_desc";
            isTrash = isTrash ?? false;

            ViewBag.IsTrash = isTrash;
            ViewBag.PageSize = pageSize;
            ViewBag.PageSizeDDL = new SelectList(pageSizeList, pageSize);
            ViewBag.ReturnListUrl = Request.Url.AbsoluteUri;

            IQueryable<Property> query = db.Properties;

            if (User.IsInRole("Property Read Private"))
            {
                query = query.Where(x => x.CreatedBy == User.Identity.Name);
            }

            ViewBag.TrashCount = query.Count(x => x.IsDelete);
            ViewBag.ListCount = query.Count(x => !x.IsDelete);

            query = PropertyTypeFilter(query, propertyTypeId);

            if (!String.IsNullOrWhiteSpace(search))
            {
                page = 1;

                query = Search(query, search.Trim());
            }

            query = Sort(query, sortOrder, sortList);

            query = query.Where(x => x.IsDelete == isTrash);

            return View(query.ToPagedList(pageNumber, (int)pageSize));
        }

        [Authorize(Roles = "Admin, Property Read Public,  Property Read Private")]
        public ActionResult _Details(int id)
        {
            Property property = db.Properties.Find(id);

            if (User.IsInRole("Property Read Private") && property.CreatedBy != User.Identity.Name)
            {
                return null;
            }

            return PartialView(property);
        }

        [Authorize(Roles = "Admin, Property Create")]
        public ActionResult Create(string returnListUrl)
        {
            ViewBag.PropertyTypeDDL = PropertyTypeSelectList(0);
            ViewBag.ReturnListUrl = returnListUrl;

            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Property Create")]
        [ValidateAntiForgeryToken]
        public ActionResult Create(PropertyCreator model, string returnListUrl)
        {
            if (ModelState.IsValid)
            {
                var property = new Property();
                property.Name = model.Name.Trim();
                property.NameId = strHp.Unsigned(property.Name);
                property.PropertyTypeId = model.PropertyTypeId;
                property.Value = model.Value;

                db.Properties.Add(property);
                db.SaveChanges();

                string propertyTypeName = db.PropertyTypes.Find(model.PropertyTypeId).Name;

                SaveHistory("Create", property.Name, propertyTypeName);
                AlertHandling("Create", property.Name, propertyTypeName);

                if (!String.IsNullOrWhiteSpace(returnListUrl))
                {
                    return Redirect(returnListUrl);
                }

                return RedirectToAction("Index");
            }

            ViewBag.PropertyTypeDDL = PropertyTypeSelectList(0);
            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [Authorize(Roles = "Admin, Property Edit Public, Property Edit Private")]
        public ActionResult Edit(int? id, string returnListUrl)
        {
            if (id == null)
            {
                return RedirectToAction("BadRequest", "Error");
            }

            Property property = db.Properties.Find(id);

            if (property == null)
            {
                return RedirectToAction("NotFound", "Error");
            }

            if (User.IsInRole("Property Edit Private") && property.CreatedBy != User.Identity.Name)
            {
                return RedirectToAction("Unauthorized", "Error");
            }

            var model = new PropertyEditor();
            model.Id = property.Id;
            model.Name = property.Name;
            model.Value = property.Value;
            model.PropertyTypeId = property.PropertyTypeId;

            ViewBag.PropertyTypeDDL = PropertyTypeSelectList(model.PropertyTypeId);
            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Property Edit Public, Property Edit Private")]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(PropertyEditor model, string returnListUrl)
        {
            if (ModelState.IsValid)
            {
                Property property = db.Properties.Find(model.Id);

                if (User.IsInRole("Property Edit Private") && property.CreatedBy != User.Identity.Name)
                {
                    return RedirectToAction("Unauthorized", "Error");
                }

                property.Name = model.Name.Trim();
                property.NameId = strHp.Unsigned(property.Name);
                property.PropertyTypeId = model.PropertyTypeId;
                property.Value = model.Value;
                property.DateModified = DateTime.Now;
                property.ModifiedBy = User.Identity.Name;

                db.Entry(property).State = EntityState.Modified;
                db.SaveChanges();

                string propertyTypeName = db.PropertyTypes.Find(model.PropertyTypeId).Name;

                SaveHistory("Edit", property.Name, propertyTypeName);
                AlertHandling("Edit", property.Name, propertyTypeName);

                if (!String.IsNullOrWhiteSpace(returnListUrl))
                {
                    return Redirect(returnListUrl);
                }

                return RedirectToAction("Index");
            }

            ViewBag.PropertyTypeDDL = PropertyTypeSelectList(model.PropertyTypeId);
            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Property Delete Public, Property Delete Private")]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id, string returnListUrl)
        {
            Property property = db.Properties.Find(id);

            if (User.IsInRole("Property Delete Private") && property.CreatedBy != User.Identity.Name)
            {
                return RedirectToAction("Unauthorized", "Error");
            }

            string propertyName = property.Name;
            string propertyTypeName = property.PropertyType.Name.ToLower();

            db.Properties.Remove(property);
            db.SaveChanges();

            SaveHistory("Delete", propertyName, propertyTypeName);
            AlertHandling("Delete", propertyName, propertyTypeName);

            if (!String.IsNullOrWhiteSpace(returnListUrl))
            {
                return Redirect(returnListUrl);
            }

            return RedirectToAction("Index", new { isTrash = true });
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Property Recycle Public, Property Recycle Private")]
        public ActionResult Recycle(int id)
        {
            Property property = db.Properties.Find(id);

            if (User.IsInRole("Property Recycle Private") && property.CreatedBy != User.Identity.Name)
            {
                return Json(-1, JsonRequestBehavior.AllowGet);
            }

            property.IsDelete = property.IsDelete ? false : true;
            property.DateModified = DateTime.Now;
            property.ModifiedBy = User.Identity.Name;

            db.Entry(property).State = EntityState.Modified;
            db.SaveChanges();

            if (property.IsDelete)
            {
                SaveHistory("Recycle-Delete", property.Name, property.PropertyType.Name);
            }
            else
            {
                SaveHistory("Recycle-Restore", property.Name, property.PropertyType.Name);
            }

            return Json(property.IsDelete ? 1 : 0, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult CheckName(string name, int? id)
        {
            name = name.Trim();

            Property property = db.Properties.FirstOrDefault(x => x.Name == name && x.Id != id);

            if (property != null)
            {
                if (!property.IsDelete)
                {
                    string url = Url.Action("Index", new { search = name, isTrash = false });
                    string result = String.Format("Tên {0} này đã tồn tại. <a href='{1}'>Chi tiết</a>.", title, url);

                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    string url = Url.Action("Index", new { search = name, isTrash = true });
                    string result = String.Format("Tên {0} này đã tạm thời bị xóa. <a href='{1}'>Chi tiết</a>.", title, url);

                    return Json(result, JsonRequestBehavior.AllowGet);
                }
            }

            return Json(true, JsonRequestBehavior.AllowGet);
        }

        #region Helpers
        private SelectList PropertyTypeSelectList(int id)
        {
            IQueryable<PropertyType> propertyTypes = db.PropertyTypes.Where(x => !x.IsDelete);

            return new SelectList(propertyTypes, "Id", "Name", id);
        }

        private void SaveHistory(string crud, string name, string group)
        {
            string type = "Property";

            DateTime dateTime = DateTime.Now;
            string userName = User.Identity.Name;
            string description = "";

            switch (crud)
            {
                case "Create":
                    description = String.Format("<b>{0}</b> tạo mới {1} {2} <b>{3}</b>", userName, title, group, name);
                    break;
                case "Edit":
                    description = String.Format("<b>{0}</b> chỉnh sửa {1} {2} <b>{3}</b>", userName, title, group, name);
                    break;
                case "Delete":
                    description = String.Format("<b>{0}</b> xóa vĩnh viễn {1} {2} <b>{3}</b>", userName, title, group, name);
                    break;
                case "Recycle-Delete":
                    description = String.Format("<b>{0}</b> xóa tạm thời {1} {2} <b>{3}</b>", userName, title, group, name);
                    break;
                case "Recycle-Restore":
                    description = String.Format("<b>{0}</b> khôi phục {1} {2} <b>{3}</b>", userName, title, group, name);
                    break;
            }

            var history = new History();
            history.DateTime = dateTime;
            history.Description = description;
            history.HistoryTypeId = db.HistoryTypes.First(x => x.Name == type).Id;

            db.Histories.Add(history);
            db.SaveChanges();
        }

        private void AlertHandling(string crud, string name, string group)
        {
            string userName = User.Identity.Name;
            string alertMessage = "";

            switch (crud)
            {
                case "Create":
                    alertMessage = String.Format("Bạn vừa tạo mới {0} {1}: <b>{2}</b>", title, group, name);
                    break;
                case "Edit":
                    alertMessage = String.Format("Bạn vừa chỉnh sửa {0} {1}: <b>{2}</b>", title, group, name);
                    break;
                case "Delete":
                    alertMessage = String.Format("Bạn vừa xóa vĩnh viễn {0} {1}: <b>{2}</b>", title, group, name);
                    break;
            }

            if (!String.IsNullOrWhiteSpace(alertMessage))
            {
                Session["alert-message-" + userName] = alertMessage;
                Session["alert-type-" + userName] = "alert-success";
            }
        }

        private IQueryable<Property> PropertyTypeFilter(IQueryable<Property> query, int? propertyTypeId)
        {
            List<PropertyType> propertyTypes = query
               .Where(x => !x.IsDelete)
               .GroupBy(x => x.PropertyType)
               .Select(x => x.Key)
               .OrderBy(x => x.Name)
               .ToList();

            ViewBag.PropertyTypeDDL = new SelectList(propertyTypes, "Id", "Name", propertyTypeId);

            if (propertyTypeId != null)
            {
                ViewBag.CategoryId = propertyTypeId;

                query = query.Where(x => x.PropertyTypeId == propertyTypeId);
            }

            return query;
        }

        private IQueryable<Property> Search(IQueryable<Property> query, string search)
        {
            ViewBag.Search = search;

            query = query.Where(x => x.Name.Contains(search));

            return query;
        }

        private IQueryable<Property> Sort(IQueryable<Property> query, string sortOrder, List<string> sortList)
        {
            ViewBag.SortOrder = sortOrder;

            foreach (string sort in sortList)
            {
                ViewData[sort + "Sort"] = sortOrder == sort + "_desc" ? sort : sort + "_desc";
            }

            if (sortOrder.Contains("_desc"))
            {
                sortOrder = sortOrder.Replace("_desc", "");
                query = query.OrderBy(sortOrder + " descending");
                ViewData[sortOrder + "Icon"] = DataTableConstant.DescSortIcon;
            }
            else
            {
                query = query.OrderBy(sortOrder);
                ViewData[sortOrder + "Icon"] = DataTableConstant.AscSortIcon;
            }

            return query;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }

            base.Dispose(disposing);
        }
        #endregion
    }
}